
#include "JniTester.h"
#include "EventManager.h"
#include "ThreadTest.h"


static const char *className = "com/dafasoft/jnicallbacktest/JniTester";


extern "C" JNIEXPORT void JNICALL Java_com_dafasoft_jnicallbacktest_JniTester_requestResult
        (JNIEnv *env, jobject obj) {
    JniTester *p = new JniTester();
    p->SetAndroidEnv(env, obj);
    p->getThreadResult();
}

void eeSleepWakeCallback(int result, void* sender) {
    JniTester *tester = (JniTester *) sender;
    tester->onResultCallback(result);
}

JniTester::JniTester() {
    EventManager::getInstance().addEvent(eeSleepWake, (void*)eeSleepWakeCallback, this);
}

void JniTester::getThreadResult() {
    ThreadTest *test = new ThreadTest();
    test->sleepThread();
}

void JniTester::onResultCallback(int result) {
    JNIEnv *env = NULL;
    int status = f_jvm->GetEnv((void **) &env, JNI_VERSION_1_4);

    bool isInThread = false;
    if (status < 0) {
        isInThread = true;
        f_jvm->AttachCurrentThread(&env, NULL);
    }

    if (f_cls != NULL) {
        jmethodID id = env->GetMethodID(f_cls, "onResult", "(I)V");
        if (id != NULL) {
            env->CallVoidMethod(f_obj, id, result);
        }
    }

    if (isInThread) {
        f_jvm->DetachCurrentThread();
    }
}


void JniTester::SetAndroidEnv(JNIEnv *env, jobject obj) {
    //获取一个java虚拟机对象
    env->GetJavaVM(&(f_jvm));
    jclass tmpClass = env->FindClass(className);
    f_cls = (jclass) env->NewGlobalRef(tmpClass);

    jobject tmpObj = (jobject) env->NewGlobalRef(obj);
    f_obj = tmpObj;
}